﻿Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.tab.*',
    'Ext.window.*',
    'Ext.tip.*',
    'Ext.layout.container.Border',
    'Ext.Component.*'
    ]);

Ext.onReady(function () {

    Ext.define('Business', {
        extend: 'Ext.data.Model',
        fields: [
	           { name: 'Id', type: 'int' },
	           { name: 'Name', type: 'string' }
	        ],
        idProperty: 'Id'
    });

    var tb = Ext.create('Ext.Toolbar', {
        xtype: 'toolbar',
        items: [{
            text: 'Criar Empresa',
            iconCls: 'iconAdd',
            handler: function () {
             //   openWindow("Business/Create", 300, 200, 'Criar empresa');
                openObjWindow(frmCreate, 310, 100, 'Criando empresa');
            }
        },
                {
                    text: 'Relatórios',
                    menu:{
                        xtype: 'menu',
                        items: [
                        {
                          text: 'Listagem geral',
                          iconCls: 'reportView',
                          handler: function(){
                            window.location = "Business/Report?Report=ShowAll&ReturnType=AsPDF"    
                          },
                          loadMask: {msg:'Carregando...'}
                        }
                        ]
                    },
                    iconCls: 'reportView',
                }                
            ]
    });

    var dsBusiness = new Ext.data.Store({
        autoLoad: true,
        autoSync: true,
        model: 'Business',
        storeId: 'Id',
        proxy: {
            type: 'rest',
            url: '../Business/GetAll',
            reader: {
                type: 'json',
                root: 'Businesses'
            },
            writer: {
                type: 'json'
            }
        }
    });

    var cellClickEvent = function(grid,rowIndex,cellIndex,e){
        frmCreate.load({
            url: 'Business/GetBusiness',
            method: 'POST',
            params: {'id': e.internalId},
            failure: function(form, action){
                Ext.Msg.alert('Erro', action.result.message);
            }
        });
        openObjWindow(frmCreate, 300, 150, 'Editando');
    }

    var grid = Ext.create('Ext.grid.Panel', {
        store: dsBusiness,
        stateful: true,
        collapsible: true,
        multiSelect: true,
        stateId: 'stateGrid',
        fit: true,
        columns: [
            {
                text: 'Código',
                flex: 0,
                sortable: true,
                width: 80,
                dataIndex: 'Id',
                renderer: function (val) { return '<div>' + val.toString() + '</div>'; }
            },
            {
                text: 'Nome',
                sortable: true,
                width: 400,
                dataIndex: 'Name'
            },            
            {
                text: 'Editar',
                width: 60,
                renderer: function (val) { return '<input id="edit-btn" type="image" src="../../Content/Themes/Aliasis/edit.gif" />'; },
                align: 'center',
                dataIndex: 'Id'
            },
            {
                text: 'Excluir',
                width: 60,
                renderer: function (val) { return '<input id="show-btn" type="image" src="../../Content/Themes/Aliasis/delete.gif" value="Pré-Visualizar" onClick="deleteBusinessWindow(' + val + ');"/>'; },
                align: 'center',
                dataIndex: 'Id'
            }
             
        ],
        listeners: {
          'cellclick' : cellClickEvent
        },
        height: 350,
        width: "100%",
        title: 'Empresas',
        renderTo: 'grid-business',
        dockedItems: tb,
        viewConfig: {
            stripeRows: true,
            enableTextSelection: true
        }
    });


    var frmCreate = new Ext.FormPanel
    ({
        layout: 'fit',
        width: '100%',
        height: '100%',
        defaults:{xtype: 'textfield'},
        trackLabels: true,
        items:
        [
        new Ext.form.Hidden({
            id: 'Id',
            value: 1,
            listeners: {
                'render': function(p){
                    this.hide();
                }
            }
        }),
        {
            fieldLabel: 'Razão Social',
            name: 'Name',
            id: 'Name',
            allowBlank: false, 
            blankText: 'Digite uma razão social válida.'
        }
        ],
        buttons:
        [{
            text: 'Salvar',
            handler: function(){
                    if(frmCreate.getForm().isValid()){
                        frmCreate.getForm().submit({
                            url: 'Business/Insert',
                            method: 'POST',
                            waitMsg: 'Criando empresa',
                            success: function(){
                                Ext.Msg.show
                                ({
                                    title: 'Sucesso',
                                    msg: 'Cadastro realizado com sucesso.',
                                    buttons: Ext.Msg.OK
                                });
                                dsBusiness.load();
                            },
                            failure: function(form, action){
                                Ext.Msg.alert('Erro', action.result.message);
                            }                         
                        });
                    }
                }
        }]
    });   
});

